#!/bin/bash
##############################################################################
# Radiance Smoke Test for CI Integration
#
# Part of E.8 regression harness - validates radiance BUFR reading parity.
# Designed to run in CI environments with radiance dataset availability.
#
# Usage:
#   ./scripts/shell/run_radiance_smoke_test.sh
#
# Environment Variables (optional):
#   MWRI_RADIANCE_DIR - Directory containing radiance BUFR files
#                       (default: /home/docker/GSI/comGSIv3.7_EnKFv1.3-mwri/test/satellite_gdas)
#   RADIANCE_SAMPLE_LIMIT - Number of observations to sample for validation
#                           (default: 1000)
#
# Exit Codes:
#   0 - All radiance parity checks passed
#   1 - Radiance data unavailable (skip test gracefully)
#   2 - Parity check failed
#   3 - Test execution error
##############################################################################

set -euo pipefail

# Configuration
RADIANCE_DIR="${MWRI_RADIANCE_DIR:-/home/docker/GSI/comGSIv3.7_EnKFv1.3-mwri/test/satellite_gdas}"
SAMPLE_LIMIT="${RADIANCE_SAMPLE_LIMIT:-1000}"
RESULTS_DIR="results/radiance_smoke_test"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

echo "=============================================================================="
echo "Radiance Smoke Test - CI Regression Harness"
echo "=============================================================================="
echo "Project root:       $PROJECT_ROOT"
echo "Radiance data:      $RADIANCE_DIR"
echo "Sample limit:       $SAMPLE_LIMIT"
echo "Results directory:  $RESULTS_DIR"
echo ""

# Check if radiance data is available
if [ ! -d "$RADIANCE_DIR" ]; then
    echo "⚠️  Radiance data directory not found: $RADIANCE_DIR"
    echo "⚠️  Skipping radiance smoke test (non-fatal)"
    exit 1
fi

# Verify key BUFR files exist
ATMS_FILE="$RADIANCE_DIR/gdas.t00z.atms.tm00.bufr_d"
MHS_FILE="$RADIANCE_DIR/gdas.t00z.1bmhs.tm00.bufr_d"
CRIS_FILE="$RADIANCE_DIR/gdas.t00z.crisf4.tm00.bufr_d"

missing_count=0
for file in "$ATMS_FILE" "$MHS_FILE" "$CRIS_FILE"; do
    if [ ! -f "$file" ]; then
        echo "⚠️  Missing BUFR file: $file"
        ((missing_count++))
    fi
done

if [ $missing_count -gt 0 ]; then
    echo "⚠️  $missing_count radiance BUFR files missing - skipping test"
    exit 1
fi

echo "✅ All radiance BUFR files found"
echo ""

# Create results directory
mkdir -p "$RESULTS_DIR"

# Change to project root for Julia execution
cd "$PROJECT_ROOT"

# Step 1: Decode radiance observations
echo "[1/3] Decoding radiance observations..."
echo ""

for instrument in "atms" "mhs" "cris"; do
    case $instrument in
        atms)
            bufr_file="$ATMS_FILE"
            ;;
        mhs)
            bufr_file="$MHS_FILE"
            ;;
        cris)
            bufr_file="$CRIS_FILE"
            ;;
    esac

    output_file="$RESULTS_DIR/${instrument}_stats.json"

    echo "  Decoding $instrument..."
    if ! JULIA_NUM_THREADS=1 julia --project=. \
        scripts/julia/capture_radiance_stats.jl \
        "$bufr_file" \
        "$output_file" \
        "$SAMPLE_LIMIT" 2>&1 | grep -E "(Wrote|ERROR|Warning)"; then
        echo "❌ Failed to decode $instrument"
        exit 3
    fi
    echo "    ✅ Wrote stats to $output_file"
done

echo ""
echo "[2/3] Running parity checks..."
echo ""

# Step 2: Run parity validation
if ! julia --project=. \
    scripts/julia/diagnostics/radiance_parity_check.jl \
    "$RESULTS_DIR" \
    "$RADIANCE_DIR" \
    "$SAMPLE_LIMIT"; then
    echo ""
    echo "❌ Radiance parity check FAILED"
    exit 2
fi

echo ""
echo "[3/3] Generating smoke test summary..."
echo ""

# Step 3: Create summary report
SUMMARY_FILE="$RESULTS_DIR/smoke_test_summary.txt"
cat > "$SUMMARY_FILE" <<EOF
Radiance Smoke Test Summary
============================

Test Date: $(date -u +"%Y-%m-%d %H:%M:%S UTC")
Sample Limit: $SAMPLE_LIMIT observations per instrument

Results:
EOF

for instrument in "ATMS" "MHS" "CrIS"; do
    stats_file="$RESULTS_DIR/$(echo $instrument | tr '[:upper:]' '[:lower:]')_stats.json"
    if [ -f "$stats_file" ]; then
        n_obs=$(jq -r '.n_observations' "$stats_file" 2>/dev/null || echo "unknown")
        n_chan=$(jq -r '.n_channels' "$stats_file" 2>/dev/null || echo "unknown")
        sat=$(jq -r '.satellite // "unknown"' "$stats_file" 2>/dev/null || echo "unknown")
        echo "  $instrument: $n_obs observations, $n_chan channels (satellite: $sat)" >> "$SUMMARY_FILE"
    else
        echo "  $instrument: ERROR - stats file not found" >> "$SUMMARY_FILE"
    fi
done

cat >> "$SUMMARY_FILE" <<EOF

Parity Status: PASSED
All radiance BUFR reading checks passed successfully.

Next Steps:
- Radiance observations can be decoded correctly
- ecCodes overlays are functioning
- Observation counts match expected samples
- Brightness temperatures are within physical ranges

Blocker: CRTM radiative transfer not yet integrated
- Radiance ASSIMILATION requires real CRTM library
- Current implementation uses placeholder physics
- Forward operator (H) and adjoint (H^T) need actual CRTM
EOF

echo "✅ Summary written to: $SUMMARY_FILE"
echo ""
cat "$SUMMARY_FILE"

echo ""
echo "=============================================================================="
echo "✅ Radiance Smoke Test PASSED"
echo "=============================================================================="
echo ""
echo "Results available in: $RESULTS_DIR"
echo ""

exit 0
